#define MaxHItems	1024

typedef struct
{
  uint32_t Value;
  uint16_t NumDat;
  uint16_t *data;
} HufStruct;

typedef struct
{
  uint16_t number;
  HufStruct *a[MaxHItems];
} HufArray;


void InsSort(HufStruct *H, HufArray *HufRec)
{
  uint16_t i = HufRec->number;
  if(i>0)  
    while(HufRec->a[i-1]->Value < H->Value)
    {
      HufRec->a[i] = HufRec->a[i-1];
      i--;
      if(i==0) break;
    }
  HufRec->a[i] = H;
  HufRec->number++;
}


#if 0
/** This procedure compute huffman code from known histogram. */
//int sq_huffman(count_t* ch_cn, uint8_t* ch_blen, unsigned* ch_blcn, int cod_num,ch_tab_t *ch_tab)
int Huffman(uint32_t *aAHuf; Bhuf *b; uint16_t Hitems)
{
//type uint16_t *PfArray;
     //PfArray=^fArray;
     
//     HufArray=record
//	number:uint16_t;
//	a:array[0..MaxHItems] of HufStruct;
//	};

/*
var a:^AhufMv absolute aAhuf;
    Hr:HufStruct;
*/
  uint16_t i,j,k;
  HufArray *HufRec;

  Hufrec = (HufArray*)malloc(sizeof(HufArray)*MaxHItems);
  memset(HufRec,sizeof(Hufrec^),0);

  for(i=0; i<HItems; i++)      	/*zarazovani novych polozek*/
    if(aAHuf[i] != 0)
    {
      Hr.value = aAHuf[i];
      Hr.NumDat = i;
      Hr.Data = NULL;
      InsSort(Hr);
    }

  for(i=0; i<HufRec->Number; i++)	/*alokace pameti*/
	{
	getmem(HufRec->a[i].data,Sizeof(uint16_t));
	HufRec->a[i].data^[0]=HufRec->a[i].NumDat;
	HufRec->a[i].NumDat=1;
	};

fillchar(b,sizeof(b),0);

while HufRec->Number>=2 do	/*Huffmanova redukce*/
	{
	k=HufRec->Number-2;

	Hr.value= HufRec->a[k].Value+HufRec->a[k+1].Value;
	Hr.numdat=HufRec->a[k].NumDat+HufRec->a[k+1].NumDat;
	getmem(Hr.data,Hr.numdat*Sizeof(uint16_t));
	for i=0 to HufRec->a[k].NumDat-1 do
		{
		Hr.data^[i]=HufRec->a[k].Data^[i];
		inc(b[Hr.data^[i]].size);
		};
	j=HufRec->a[k].NumDat;
	for i=0 to HufRec->a[k+1].NumDat-1 do
		{
		Hr.data^[i+j]=HufRec->a[k+1].Data^[i];
		inc(b[Hr.data^[i+j]].size);
		};


	dec(HufRec->Number,2);
	freemem(HufRec->a[k].data,HufRec->a[k].NumDat*Sizeof(uint16_t));
	HufRec->a[k].NumDat=0;
	HufRec->a[k].Data=nil;
	freemem(HufRec->a[k+1].data,HufRec->a[k+1].NumDat*Sizeof(uint16_t));
	HufRec->a[k+1].NumDat=0;
	HufRec->a[k+1].Data=nil;

	InsSort(Hr);
	};


for i=0 to HufRec->Number-1 do
	{
	freemem(HufRec->a[i].data,HufRec->a[i].NumDat*Sizeof(uint16_t));
	HufRec->a[i].NumDat=0;
	HufRec->a[i].Data=nil;
	};
for i=0 to HItems do b[i].Number=i;
dispose(HUfrec);
};
#endif

